package com.example.books;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.books.data.User;

import org.litepal.LitePal;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText edtUsername;
    private EditText edtPassword;
    private Button LoginBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        addUser();
    }

    private void addUser() {
        User user =new User();
        user.setId(0);
        user.setUserName("zhangsan");
        user.setPassWord("123");
        user.save();
        user =new User(0,"lisi","456");
        user.save();
        user.setId(0);
        user =new User();
        user.setUserName("wanwu");
        user.setPassWord("789");
        user.save();
    }

    private void initView() {
        edtUsername = (EditText) findViewById(R.id.edtUsername);
        edtPassword = (EditText) findViewById(R.id.edtPassword);
        LoginBtn = (Button) findViewById(R.id.LoginBtn);
        LoginBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.LoginBtn:
                if(login()){
                    Intent intent = new Intent(MainActivity.this,UserActivity.class);
                    startActivity(intent);
                    finish();
                }else {
                    Toast.makeText(MainActivity.this,"用户密码错误",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * 检测密码
     * @return
     */
    private boolean login() {
        List<User> users = LitePal.where("userName = ?", edtUsername.getText().toString().trim()).find(User.class);
        if(users.size()>0&& users.get(0).getPassWord().equals(edtPassword.getText().toString().trim())){
            SharedPreferences.Editor edit = getSharedPreferences("id",MainActivity.MODE_PRIVATE).edit();
            edit.putInt("sid",users.get(0).getId());
            edit.putString("sname",users.get(0).getUserName());
            edit.apply();
           return true;
        }

        return false;
    }

}
